package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQueryObject;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.sun.jna.platform.win32.Winspool;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class CarPackageAuditImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public InputStream processImg(Long id) {
        CarPackageAudit audit = this.get(id);

        String instanceId = audit.getInstanceId();// 获取流程实例ID
        // 判断是否正在审核中
        List<String> list = null;
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            list = runtimeService.getActiveActivityIds(instanceId);
        } else {
            list = new ArrayList<>();
        }

        // 获取流程定义id
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(audit.getBpmnInfoId());
        // 需要传入流程定义id
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator= new DefaultProcessDiagramGenerator();
        InputStream inputStream = generator.generateDiagram(model, list, Collections.emptyList(), "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.get(id);
        // 修改审核对象状态
        carPackageAuditMapper.changeAuditStatus(audit.getId(),CarPackageAudit.STATUS_CANCEL);
        // 修改服务状态
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(audit.getServiceItemId());
        // serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_REPLY);
        serviceItemMapper.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        // 删除流程实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"流程撤销");

    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        // 合理化校验，判断是否正在审核中
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("非法参数");
        }

        // 判断是否是当前用户
        Long userId = ShiroUtils.getUserId();
        Long auditorId = audit.getAuditorId();
        if (!userId.equals(auditorId)) {
            throw new BusinessException("非法参数");
        }

        String userName = ShiroUtils.getUser().getUserName();
        // 判断是否同意
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) { // 同意
            info = userName + "审批同意" + info;
        } else if (CarPackageAudit.STATUS_REJECT.equals(auditStatus)) { // 拒绝
            info = userName + "审批拒绝" + info;
        }

        audit.setInfo(audit.getInfo()+ "</br>" +info);

        // 根据流程实例id获取任务
        Task task1 = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        taskService.setVariable(task1.getId(),"auditStatus",auditStatus.longValue());

        taskService.complete(task1.getId());

        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) { // 同意
            // 根据流程实力id查询下一个任务的id
            Task task2 = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
            // 看是否有下一个流程节点
            if (task2 != null ) {
                // 设置ID
                audit.setAuditorId(Long.parseLong(task2.getAssignee()));
            } else {
                // 走完就把ID设置为空
                audit.setAuditorId(null);
                // 更新服务单
                audit.setStatus(CarPackageAudit.STATUS_PASS);
                serviceItemMapper.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }
        } else if (CarPackageAudit.STATUS_REJECT.equals(auditStatus)) { // 拒绝
            // 拒绝就把ID设置为空
            audit.setAuditorId(null);

            audit.setStatus(CarPackageAudit.STATUS_REJECT);
            // 服务也要设置通过审核
            serviceItemMapper.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        }

        carPackageAuditMapper.updateByPrimaryKey(audit);

    }
}
